package com.mall.shopping.services;


import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;

import com.mall.commons.tool.exception.BizException;

import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;

import org.apache.dubbo.common.utils.CollectionUtils;

import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * @author 谭涛
 */


import tk.mybatis.mapper.entity.Example;




@Slf4j
@Service
@Component

public class CartServiceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;


    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        CartListByIdResponse response = new CartListByIdResponse();
        List<CartProductDto> cartProductDtos = new ArrayList<>();
        try {
            request.requestCheck();
            // TODO: 2020/12/20
            RMap<Long, CartProductDto> rMap = redissonClient.getMap(request.getUserId().toString());
            Set<Map.Entry<Long, CartProductDto>> entries = rMap.entrySet();
            for (Map.Entry<Long, CartProductDto> entry : entries) {
                CartProductDto productDto = entry.getValue();
                cartProductDtos.add(productDto);
            }
            response.setCartProductDtos(cartProductDtos);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            log.error("CartServiceImpl.getCartListById occur Exception :" + e);
        }
        return response;
    }




    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        Example example = new Example(Item.class);
        example.createCriteria().andEqualTo("id", request.getProductId());
        List<Item> items = itemMapper.selectByExample(example);
        AddCartResponse response = new AddCartResponse();
        try {
            if (CollectionUtils.isEmpty(items)) {
                throw new BizException(ShoppingRetCode.DB_EXCEPTION.getCode(), ShoppingRetCode.DB_EXCEPTION.getMessage());
            }
            CartProductDto cartProductDto = CartItemConverter.item2Dto(items.get(0));
            cartProductDto.setProductNum(request.getProductNum());
            cartProductDto.setChecked("true");
            RMap<Long, CartProductDto> rMap = redissonClient.getMap(request.getUserId().toString());
            CartProductDto productDto = rMap.get(request.getUserId());
            if (productDto != null) {
                // 购物车中已经有相同的商品，商品数量增加即可
                productDto.setProductNum(productDto.getProductNum() + request.getProductNum());
                rMap.put(request.getProductId(), cartProductDto);
            } else {
                rMap.put(request.getProductId(), cartProductDto);
            }
            log.info("购物车新增商品: " + cartProductDto.getProductName());
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            BizException exception = (BizException) e;
            response = new AddCartResponse();
            response.setCode(exception.getErrorCode());
            response.setMsg(exception.getMessage());
            return response;
        }
    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try{
            RMap<Long, CartProductDto> rMap = redissonClient.getMap(request.getUserId().toString());
            CartProductDto cartProductDto = rMap.get(request.getProductId());
            cartProductDto.setChecked(request.getChecked());
            cartProductDto.setProductNum(request.getProductNum());
            rMap.put(cartProductDto.getProductId(),cartProductDto);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        }catch (Exception e){
            log.error("CartsController.updateCartNum occur Exception:" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        //todo zp
        return response;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        return null;
    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        return null;
    }

    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        return null;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }
}
